package org.easymis.air.southwest.modules.organize.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.easymis.air.southwest.common.utils.SouthwestConstant;
import org.easymis.air.southwest.modules.organize.service.MemberMng;
import org.easymis.air.southwest.modules.organize.service.OaMessageMng;
import org.easymis.air.southwest.modules.organize.service.OrganizeFunctionMng;
import org.easymis.commons.web.springmvc.JsonApi;
import org.easymis.commons.web.springmvc.JsonMessage;
import org.easymis.entitys.mybatis.dto.Member;
import org.easymis.entitys.mybatis.dto.OaMessage;
import org.easymis.entitys.mybatis.dto.Organize;
import org.easymis.entitys.mybatis.dto.OrganizeFunction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.google.code.kaptcha.Producer;


@Controller
@RequestMapping("/login/")
public class OrganizeLoginController {
	private static final String LOG_ERR_MSG = "帐号或密码错误！";
	private static final String LOG_ERR_ORG_MSG = "没有找到该用户的组织！";
	private static final String LOG_ERROR_MSG = "帐号或密码不能为空！";
	@Autowired
	private Producer producer;
	@Autowired
	private MemberMng memberMng;
	@Autowired
	private OaMessageMng messageMng;
	@Autowired
	private OrganizeFunctionMng functionMng;
	
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response,HttpSession session)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
       // ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);
        session.setAttribute("validateCode", text.toUpperCase());
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
	}
	/**
	 * 跳转登录页面
	* @Title: login
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param @param session
	* @param @param model
	* @param @param request
	* @param @return
	* @param @throws Exception    设定文件
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping(value = "index")
	public String login(HttpSession session, ModelMap model, HttpServletRequest request) throws Exception {		
		String memberName = request.getParameter("memberName");// 账户名
		String password = request.getParameter("password");// 用户密码
		// FIXME 由于系统本身原因初始化进入的时候就调用该接口，而传值为空直接略过了前端效验，进入了该方法。
		if (memberName == null || password == null) {
			request.setAttribute("loginState", LOG_ERROR_MSG);
			request.setAttribute("base", "http://demo.easymis.cn");
			return "login";
		} else {
			// 通过用户的手机号取用户的信息
			Member memberInfo=memberMng.findByMobileLogin(memberName);
			// 取出的用户信息：若为空就直接返回登录页面，若有值就判断密码是否相等。[ TODO 后边若做MD5加密加盐再更改]
			if (memberInfo == null || !password.equals(memberInfo.getPassword())) {
				request.setAttribute("loginState", LOG_ERR_MSG);
				request.setAttribute("base", "http://demo.easymis.cn");
				return "login";
			}
			request.setAttribute("base", "http://demo.easymis.cn");
			// 通过当前的用户去判断该用户是否属于多个公司旗下
			List<Organize> organizeList= memberMng.findByMembernameOnOrganize(memberInfo.getMemberId());
			HashMap<String, Object> params = new HashMap<>();
			// 如果该员工只属于一个公司下就直接赋权并进入系统，多个就页面弹出让用户选择自己准备进入的组织。[可写个方法共用]
			if (organizeList != null && organizeList.size() == 1) {
				Organize organize =organizeList.get(0);
				//通过member.getMemberId() + orgId重新获取用户信息
				HashMap<String, Object> memberparams = new HashMap<>();
				memberparams.put("memberId", memberInfo.getMemberId());
				memberparams.put("orgId", organize.getOrgId());
				Member staffInfo = memberMng.findByMemberIdOrgId(memberparams);
	
				//通过用户的staffId取当前公司下的菜单
				params.put("staffId", staffInfo.getStaffId());
				params.put("orgId", organize.getOrgId());
				List<OrganizeFunction> menus = memberMng.getListOnStaff(params);
				memberInfo.setMenus(menus);
				OrganizeFunction bean =new OrganizeFunction();
				bean.setLevel(1);
				bean.setStaffId(staffInfo.getStaffId());
				bean.setOrgId(organize.getOrgId());
				List<OrganizeFunction> menusLevel1=functionMng.getListByStaff(bean);
				//获得接收消息列表
				OaMessage message= new OaMessage();
				message.setOrgId(organize.getOrgId());
				message.setReceiveId(memberInfo.getStaffId());				
				
				memberInfo.setStaffId(staffInfo.getStaffId());
				memberInfo.setStaffName(staffInfo.getStaffName());
				memberInfo.setOrgId(organize.getOrgId());
				memberInfo.setOrgName(organize.getOrgName());
				session.setAttribute("userInfo", memberInfo);   // 保存用户信息				
				model.put("menusLevel1", menusLevel1);
				request.setAttribute("messageList", messageMng.getList(message));
				model.put("messageNum", messageMng.getList(message).size());
			} else if (organizeList != null && organizeList.size() > 1) {
				request.setAttribute("organizeList", organizeList);
				session.setAttribute("userInfo", memberInfo);   // 保存用户信息
				return "login_organize_list";
			} else {
				// 用户没有组织的情况等异常情况处理
				request.setAttribute("loginState", LOG_ERR_ORG_MSG);
				request.setAttribute("base", "http://demo.easymis.cn");
				return "login";
			}
		}
		return "index";
	}

	/**
	 * Ajax登录验证
	* @Title: login
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param @param session
	* @param @param model
	* @param @param request
	* @param @return
	* @param @throws Exception    设定文件
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping(value = "ajax/index")
	public Object ajaxLogin(HttpSession session, ModelMap model, HttpServletRequest request) throws Exception {		
		String memberName = request.getParameter("memberName");// 账户名
		String password = request.getParameter("password");// 用户密码
		JsonApi jsonApi = new JsonApi(2);
		// FIXME 由于系统本身原因初始化进入的时候就调用该接口，而传值为空直接略过了前端效验，进入了该方法。
		if (memberName == null || password == null) {
			request.setAttribute("base", "http://demo.easymis.cn");
			jsonApi = new JsonApi(2,"用户名和密码不能为空");
		} else {
			// 通过用户的手机号取用户的信息
			Member memberInfo=memberMng.findByMobileLogin(memberName);
			// 取出的用户信息：若为空就直接返回登录页面，若有值就判断密码是否相等。[ TODO 后边若做MD5加密加盐再更改]
			if (memberInfo == null || !password.equals(memberInfo.getPassword())) {
				jsonApi = new JsonApi(2,"密码错误");
			}
			request.setAttribute("base", "http://demo.easymis.cn");
			// 通过当前的用户去判断该用户是否属于多个公司旗下
			List<Organize> organizeList= memberMng.findByMembernameOnOrganize(memberInfo.getMemberId());
			HashMap<String, Object> params = new HashMap<>();
			// 如果该员工只属于一个公司下就直接赋权并进入系统，多个就页面弹出让用户选择自己准备进入的组织。[可写个方法共用]
			if (organizeList != null && organizeList.size() == 1) {
				//通过member.getMemberId() + orgId重新获取用户信息
				Organize organize =organizeList.get(0);
				HashMap<String, Object> memberparams = new HashMap<>();
				memberparams.put("memberId", memberInfo.getMemberId());
				memberparams.put("orgId", organize.getOrgId());
				Member member2 = memberMng.findByMemberIdOrgId(memberparams);
				//通过用户的staffId取当前公司下的菜单
				params.put("staffId", member2.getStaffId());
				params.put("orgId", organize.getOrgId());
				List<OrganizeFunction> menus = memberMng.getListOnStaff(params);
				memberInfo.setMenus(menus);
				OrganizeFunction bean =new OrganizeFunction();
				bean.setLevel(1);
				bean.setStaffId(member2.getStaffId());
				List<OrganizeFunction> menusLevel1=functionMng.getList(bean);
				
				memberInfo.setStaffId(member2.getStaffId());
				memberInfo.setOrgName(organize.getOrgName());
				session.setAttribute("userInfo", memberInfo);   // 保存用户信息
				model.put("menusLevel1", menusLevel1);
				jsonApi = new JsonApi(1);
			} else if (organizeList != null && organizeList.size() > 1) {
				session.setAttribute("userInfo", memberInfo);   // 保存用户信息
				jsonApi = new JsonApi(1,organizeList);
			} else {
				// 用户没有组织的情况等异常情况处理
				request.setAttribute("loginState", LOG_ERR_ORG_MSG);
				jsonApi = new JsonApi(2,"登录失败请稍后再试");
			}
		}
		return jsonApi;
	}
	/**
	 * @see 按组织或公司方式登录
	* @Title: selectOrganize
	* @Description: TODO(这里用一句话描述这个方法的作用)
	* @param @param orgId
	* @param @param session
	* @param @param model
	* @param @param request
	* @param @return
	* @param @throws Exception    设定文件
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping(value = "loginByOrganize")
	public String selectOrganize(String orgId, HttpSession session, ModelMap model, HttpServletRequest request)
			throws Exception {
		Member member = (Member) session.getAttribute("userInfo");
		request.setAttribute("base", "http://demo.easymis.cn");
		try {
			// 通过member.getMemberId() + orgId重新获取用户信息
			HashMap<String, Object> memberparams = new HashMap<>();
			memberparams.put("memberId", member.getMemberId());
			memberparams.put("orgId", orgId);
			Member member2 = memberMng.findByMemberIdOrgId(memberparams);
			member2.setOrgId(orgId);

			HashMap<String, Object> params = new HashMap<>();
			params.put("staffId", member2.getStaffId());
			params.put("orgId", orgId);
			List<OrganizeFunction> menus = memberMng.getListOnStaff(params);
			member2.setMenus(menus);
			OrganizeFunction bean = new OrganizeFunction();
			bean.setLevel(1);
			bean.setStaffId(member2.getStaffId());
			bean.setOrgId(orgId);
			List<OrganizeFunction> menusLevel1 = functionMng.getList(bean);
			List<Organize> organizeList = memberMng.findByMembernameOnOrganize(member.getMemberId());
			// 获得接收消息列表
			OaMessage message = new OaMessage();
			message.setOrgId(member2.getOrgId());
			message.setReceiveId(member2.getStaffId());

			session.setAttribute("userInfo", member2);// 保存用户信息
			model.put("userInfo", member2);
			model.put("menusLevel1", menusLevel1);
			model.put("organizeList", organizeList);

			model.put("messageList", messageMng.getList(message));
			model.put("messageNum", messageMng.getList(message).size());
		} catch (Exception e) {
			return "login";
		}
		return "index";
	}
	@RequestMapping(value = "ajax/loginByOrganize")
	@ResponseBody
	public Object  selectOrganizeByAiax(String orgId,ModelMap model, HttpServletRequest request, HttpSession session) {
		Member member =(Member)session.getAttribute("userInfo");
		JsonApi jsonApi = new JsonApi(false);
		if (member == null) {
			jsonApi = new JsonApi(2, JsonMessage.LOGINFAILED);
		} else {
/*			CrmLeads param = new CrmLeads();
			param.setOrgId(member.getOrgId());
			PageHelper.startPage(SimplePage.cpn(page), SimplePage.cps(pageSize));
			List<CrmLeads> beanList = service.getList(param);
			List<CrmLeads> vList= new ArrayList<CrmLeads>();
			PageInfo<CrmLeads> p = new PageInfo<CrmLeads>(beanList);*/

			jsonApi = new JsonApi(1,null);
		}
		return jsonApi;
	}
	/**
	 * 
	* @Title: queryByAjax
	* @Description: TODO(获取二级菜单)
	* @param @param menuId
	* @param @param request
	* @param @param response
	* @param @param model
	* @param @param session
	* @param @return    设定文件
	* @return Map<String,Object>    返回类型
	* @throws
	 */
	@RequestMapping(value = "ajax/menu")
	@ResponseBody
	public Map<String, Object> queryByAjax(String menuId,HttpServletRequest request, HttpServletResponse response, ModelMap model, HttpSession session) {
		Member user =(Member)session.getAttribute("userInfo");
		Map<String, Object> result = new HashMap<String, Object>();
		if (user == null) {
			return result;
		}
		OrganizeFunction bean =new OrganizeFunction();
		bean.setOrgId(user.getOrgId());
		bean.setStaffId(user.getStaffId());
		//bean.setParentId(menuId);
		List<OrganizeFunction> menuLevel2=functionMng.getList(bean);

		result.put("menuLevel2", menuLevel2);
		result.put("base", "http://demo.easymis.cn");
		return result;
	}
	/**
	 * 用户退出系统方法
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "logout")
	public ModelAndView userLogout(HttpServletRequest request, HttpSession session) throws Exception {
		//设置session失效
		session.invalidate();
		return  new ModelAndView(new RedirectView(SouthwestConstant.SITE_URL+"/login.html")); 
	}
	@RequestMapping(value = "joinOrganize")
	public String joinOrganize(HttpSession session, ModelMap model, HttpServletRequest request) throws Exception {
		Member member =(Member)session.getAttribute("userInfo");
		model.put("userInfo", member);
		request.setAttribute("base", "http://demo.easymis.cn");
		return "join_organize";
		
	}
	/**
	 * 查询用户是否存在
	 * @param request
	 * @param session
	 * @param mobile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "checkMobile")
	@ResponseBody
	public Boolean checkMobile(HttpServletRequest request, HttpSession session, String mobile) throws Exception {
		Member member = memberMng.findByMobile(mobile);
		if (member != null) {
			return false;
		}
		return true;
	}
	/**
	 * 查询用户是否存在
	 * @param request
	 * @param session
	 * @param mobile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "checkPassword")
	@ResponseBody
	public Boolean checkPassword(HttpServletRequest request, HttpSession session, String memberName,String password) throws Exception {
		Member member = memberMng.findByMobile(memberName);
		if (member != null&& member.getPassword().equals(password.trim())) {
			return true;
		}
		return false;
	}
	@RequestMapping(value = "checkUserCaptcha")
	@ResponseBody
	public Boolean checkUserCaptcha(HttpServletRequest request, HttpSession session, String userCaptcha) throws Exception {
		String validateCode =(String) session.getAttribute("validateCode");
		if(StringUtils.isEmpty(validateCode)||StringUtils.isEmpty(userCaptcha))
			return false;
		
		return validateCode.equals(userCaptcha.toUpperCase());

	}

}
